package com.gouaixin.bee.beeframework2.activity;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.os.Handler;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.ab.util.AbImageUtil;
import com.gouaixin.bee.beeframework2.tool.mLog;
import com.google.gson.Gson;
import com.google.gson.JsonSyntaxException;
import com.google.gson.reflect.TypeToken;
import com.gouaixin.bee.beeframework2.MyAPI;
import com.gouaixin.bee.beeframework2.R;
import com.gouaixin.bee.beeframework2.extra.im.ChatData;
import com.gouaixin.bee.beeframework2.extra.im.TextAdapter;
import com.gouaixin.bee.beeframework2.bean.getMessageResponse;
import com.gouaixin.bee.beeframework2.tool.PreferencesUtils;
import com.gouaixin.bee.beeframework2.tool.XHttpUtils;
import com.gouaixin.bee.beeframework2.bean.BaseModel;
import com.lidroid.xutils.HttpUtils;
import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.RequestParams;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.callback.RequestCallBack;
import com.lidroid.xutils.http.client.HttpRequest;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.assist.FailReason;
import com.nostra13.universalimageloader.core.assist.ImageLoadingListener;

import org.json.JSONException;
import org.json.JSONObject;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Random;


import cn.bmob.v3.BmobPushManager;

/**
 * Created by Administrator on 2015/3/10.
 */
//聊天消息界面（使用sp）
public class C1_LiaotianJiemianTestActivity extends Activity {
    Context context = C1_LiaotianJiemianTestActivity.this;

    String id = "聊天界面";
    String cid = "";
    String msg = "";
    String time = "";
    String flag="";

    ImageView back;//返回按钮
    TextView title;//标题姓名
    EditText input;//输入框
    TextView send;//发送按钮

    ListView list;//聊天列表
    ArrayList<ChatData> datas = new ArrayList<ChatData>();
    TextAdapter adapter;

    RelativeLayout footer;
    RelativeLayout suoyao;

    String hericon = "";//保存的头像网址
    String name = "";//机器人name
    String qianming = "";//机器人的内心独白
    BmobPushManager bmobPushManager;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.c1_liaotianjiemian);
        bmobPushManager = new BmobPushManager(this);
        initIntent();
        initHead();
        initDubai();
        initFoot();

    }

    @Override
    protected void onPause() {
        super.onPause();
        Gson gson = new Gson();
        String str = gson.toJson(datas);
        mLog.e("暂停时保存的聊天记录：" + id + "liao=" + str);
        PreferencesUtils.putString(context, id + "liao", str);

        if(flag.equals("0")){
            PreferencesUtils.putInt(context, "liaoStatus", 0);

        }


//        /***
//         * liaoStatus（聊天状态）：0（程序在后台）；1（程序在前端显示，非聊天界面）；2（显示聊天界面）
//         */
//        PreferencesUtils.putInt(context, "liaoStatus", 0);
//        int liaoStatus = PreferencesUtils.getInt(context, "liaoStatus");
//        mLog.e("当前的聊天状态：liaoStatus=" + liaoStatus);

    }

    @Override
    protected void onResume() {
        super.onResume();

        cid=PreferencesUtils.getString(context,"jid","");

        /***
         * liaoStatus（聊天状态）：0（程序在后台）；1（程序在前端显示，非聊天界面）；2（显示聊天界面）
         */
        PreferencesUtils.putInt(context, "liaoStatus", 2);
        int liaoStatus = PreferencesUtils.getInt(context, "liaoStatus");
        mLog.e("当前的聊天状态：liaoStatus=" + liaoStatus);


        mLog.e("恢复运行时读取的聊天记录：");
        String dataStr = PreferencesUtils.getString(context, id + "liao", "");
        if (dataStr != null && !dataStr.equals("")) {
            Gson gson = new Gson();

            List<ChatData> ps = gson.fromJson(dataStr, new TypeToken<List<ChatData>>() {
            }.getType());
            mLog.e("恢复运行时读取的聊天记录：tostring=" + ps.toString());
            datas = (ArrayList<ChatData>) ps;

            for (int i = 0; i < ps.size(); i++) {
                ChatData p = ps.get(i);
                mLog.e("恢复运行时读取的聊天记录：content=" + p.getContent());
            }

        }

        initContent();


    }

    private void addChatFriend() {

        BaseModel.setCallBackLister(new BaseModel.CallBackLister() {
            @Override
            public String onCallBack(String url, String data) {


                return url;
            }
        });

        RequestParams params=new RequestParams();
        params.addBodyParameter("jid", id);
        params.addBodyParameter("cid", cid);
        params.addBodyParameter("text", msg);
        params.addBodyParameter("time", time);
        BaseModel.post(MyAPI.addchatfriend, params);
    }


    private void initDubai() {
        RelativeLayout dubaiRL;
        TextView dubai_name;
        ImageView dubai_icon;
        final ImageView icon;
        TextView dubai_content;
        dubaiRL = (RelativeLayout) findViewById(R.id.dubai);
        dubai_name = (TextView) findViewById(R.id.dubai_name);
        dubai_icon = (ImageView) findViewById(R.id.dubai_icon);
        icon = (ImageView) findViewById(R.id.icon);
        dubai_content = (TextView) findViewById(R.id.dubai_content);

        dubai_name.setText(name + "的内心独白");

        dubai_content.setText(qianming);

        ImageLoader imageLoader = ImageLoader.getInstance();

        imageLoader.loadImage(hericon,new ImageLoadingListener() {
            @Override
            public void onLoadingStarted(String s, View view) {

            }

            @Override
            public void onLoadingFailed(String s, View view, FailReason failReason) {

            }

            @Override
            public void onLoadingComplete(String s, View view, Bitmap bitmap) {
                icon.setBackground(AbImageUtil.bitmapToDrawable(bitmap));

            }

            @Override
            public void onLoadingCancelled(String s, View view) {

            }
        });

//        imageLoader.displayImage(jicon, icon);

        dubaiRL.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mLog.i("进入用户资料界面：jid=" + id);
                Intent it = new Intent().setClass(context, B6_ziliaoActivity.class);
//                it.putExtra("jid", jid);
                it.putExtra("HerId",id);
                startActivity(it);

            }
        });


    }


    /**
     * 脚部的监听
     */
    boolean isFirstLiao;//是否第

    private void initFoot() {
        footer = (RelativeLayout) findViewById(R.id.footer);
        suoyao = (RelativeLayout) findViewById(R.id.suoyao);

        input = (EditText) findViewById(R.id.input);
        send = (TextView) findViewById(R.id.send);
        send.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String msg = input.getText().toString();
                mLog.e("测试时，一直可以正常聊天,正式版删除");
                send(msg);
                PreferencesUtils.putBoolean(context, "isFirstLiao", false);


//
//                /***
//                 *测试聊天好友列表接口
//                 */
//                try {
//                    mLog.e("测试聊天好友列表接口：");
//
//                    JSONObject json = new JSONObject();
//                    json.put("cid","08122536");
//
//                    mLog.e("聊天好友列表：请求=" + json.toString());
//                    String url="http://jiekou.hydgyx.com/api/interface_chafriends.php";
//                    mLog.e("聊天好友列表：url=" + url);
//                    postJsonUtils.postJson(context, url, json);
//                    postJsonUtils.setResponseLister(new postJsonUtils.ResponseLister() {
//                        @Override
//                        public void onMyResponse(JSONObject obj) {
//                            mLog.e("聊天好友列表：响应=" + obj.toString());
//                        }
//                    });
//                } catch (Exception e) {
//                    // TODO Auto-generated catch block
//                    mLog.e("json异常"+e.getMessage());
//                    e.printStackTrace();
//                }
//


//                BmobChatManager mBmobChatManager= BmobChatManager.getInstance(context);

//
//                /***
//                 * 利用bmob发送消息给指定id
//                 */
//                try {
//                    ChatData chatData=new ChatData();
//                    chatData.setContent(msg);
//                    chatData.setFname(BmobUser.getCurrentUser(context, USER.class).getName());
//                    mLog.e("fname="+BmobUser.getCurrentUser(context, USER.class).getName());
//                    chatData.setTime(new Date().getTime() + "");
//                    String fid= BmobUser.getCurrentUser(context).getUsername();
//                    chatData.setFid(fid);
//                    chatData.setTid("25973835");
//                    String gsonstr = new Gson().toJson(chatData);
//                    bmobPushManager.pushMessageAll(new JSONObject(gsonstr));
//                    mLog.e("发送消息:成功："+gsonstr);
//                } catch (Exception e) {
//                    mLog.e("发送消息:失败："+e.getMessage());
//                    e.printStackTrace();
//                }


                //随机5~10秒后,机器人回复一条消息
                int temp = new Random().nextInt(5);
                mHandler.postDelayed(mRunnable, 1000 * (5 + temp));


//                if(msg.equals("")){
//                    AbToastUtil.showToast(context, "聊天内容不能为空");
//                    return;
//                }
//
//
//                //读取本地保存的icon
//                icon= PreferencesUtils.getString(context,"icon","");
//                 isFirstLiao=PreferencesUtils.getBoolean(context,"isFirstLiao",true);
//
//
//                //头像不存在
//                if(icon.equals("")){
//                    mLog.e("头像不存在:进入上传头像界面");
//                    Intent it = new Intent().setClass(context, B19_shangchuanTouxiangActivity.class);
//                    it.putExtra("isLiaotian", true);
//                    startActivity(it);
//                }
//                //头像存在且没有发过一条消息
//                else if(!icon.equals("")&&isFirstLiao==true){
//                    mLog.e("头像存在且没有发过一条消息:可以正常发送一条消息");
//                    send(msg);
//                    PreferencesUtils.putBoolean(context,"isFirstLiao",false);
//
//
//                    //随机1~3秒后,机器人回复一条消息
//                    int temp=new Random().nextInt(3);
//                    mHandler.postDelayed(mRunnable, 1000*(1+temp));
//
//
//                }
//
//                //头像存在
//                else {
//                    mLog.e("头像存在且发过一条消息:跳转到促销活动界面");
//                    Intent it = new Intent().setClass(context, B10_chuxiaoActivity.class);
//                    startActivity(it);
//
//                }

            }
        });


//        //头像不存在
//        if(icon.equals("")){
//            footer.setVisibility(View.VISIBLE);
//            suoyao.setVisibility(View.GONE);
//        }
//        //头像存在
//        else {
//            suoyao.setVisibility(View.VISIBLE);
//            footer.setVisibility(View.GONE);
//            suoyao.setOnClickListener(new View.OnClickListener() {
//                @Override
//                public void onClick(View v) {
//                    mLog.e("进入促销活动界面");
//                    Intent it = new Intent().setClass(context, B10_chuxiaoActivity.class);
//                    startActivity(it);
//                }
//            });
//        }
    }

    /**
     * 获取聊天好友列表
     *
     * @param cid
     */
    private void getChatFriends(String cid) {
        String url = "http://jiekou.hydgyx.com/api/interface_chatfriends.php";
        mLog.e("获取聊天好友列表： url=" + url);
        final String[] result = {""};

        RequestParams params = new RequestParams();
        params.addBodyParameter("cid", cid);

        mLog.e("获取聊天好友列表： 请求=" + params.toString());

        HttpUtils http = new HttpUtils();
        http.send(HttpRequest.HttpMethod.POST,
                url,
                params,
                new RequestCallBack<String>() {
                    @Override
                    public void onLoading(long total, long current, boolean isUploading) {
                        mLog.e(current + "/" + total);
                    }

                    @Override
                    public void onSuccess(ResponseInfo<String> responseInfo) {
                        mLog.e("获取聊天好友列表：响应=" + XHttpUtils.Unicode2Chinese(responseInfo.result));
                        result[0] = XHttpUtils.Unicode2Chinese(responseInfo.result);
                    }

                    @Override
                    public void onStart() {
                        mLog.e("开始请求：");
                    }

                    @Override
                    public void onFailure(HttpException error, String msg) {
                        mLog.e("请求故障：" + msg);
                    }
                }
        );
    }


    /**
     * 回复消息的方法
     */


    private void huifu() {


    }

    private void initIntent() {
        Intent it = getIntent();
        id = it.getStringExtra("jid");
        name = it.getStringExtra("jname");
        hericon = it.getStringExtra("icon");
        qianming = it.getStringExtra("qianming");
        flag=it.getStringExtra("flag");//是否是从弹出框进入
    }

    /**
     * 内容区域的监听
     */
    private void initContent() {
        list = (ListView) findViewById(R.id.list);
        adapter = new TextAdapter(datas, context);

        adapter.setIcon(hericon);


        list.setAdapter(adapter);

        if (datas.size() == 0) {
//            recevie();//如果没有消息，就默认接受一条消息
            getWebMessage("", "");
        }

    }

    /**
     * 头部的监听
     */
    private void initHead() {
        //顶部
        back = (ImageView) findViewById(R.id.back);
        title = (TextView) findViewById(R.id.title);
        title.setText(name);
        back.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });

    }

    String[] welcome_array;
    String welcome_tip;

    /**
     * 从本地获取欢迎语
     *
     * @return
     */    private String getRandomWelcomeTips() {
        welcome_array = this.getResources()
                .getStringArray(R.array.welcome_tips);
        int index = (int) (Math.random() * (welcome_array.length - 1));
        welcome_tip = welcome_array[index];
        return welcome_tip;
    }




    /**
     * 随机获取语言库
     */
    private void getWebMessage(String gender, String cishu) {
        String url = "http://jiekou.hydgyx.com/api/interface_getmessage.php";
        mLog.e("随机获取语言库： url=" + url);
        final String[] result = {""};

        RequestParams params = new RequestParams();
        params.addBodyParameter("Gender", "1");
        params.addBodyParameter("cishu", "1");

        HttpUtils http = new HttpUtils();
        http.send(HttpRequest.HttpMethod.POST,
                url,
                params,
                new RequestCallBack<String>() {
                    @Override
                    public void onSuccess(ResponseInfo<String> responseInfo) {
                        mLog.e("随机获取语言库：响应=" + XHttpUtils.Unicode2Chinese(responseInfo.result));
                        result[0] = XHttpUtils.Unicode2Chinese(responseInfo.result);
                        if (!result[0].equals("")) {
                            try {
                                getMessageResponse obj = new Gson().fromJson(result[0], getMessageResponse.class);

                                String msg = obj.getMessage();
                                mLog.e("随机获取语言库：msg=" + msg);

                                recevie(msg);
                            } catch (JsonSyntaxException e) {
                                e.printStackTrace();
                                mLog.e("随机获取语言库：出错：" + e.getMessage());
                            }

                        }

                    }

                    @Override
                    public void onFailure(HttpException error, String msg) {
                        mLog.e("请求故障：" + msg);
                    }
                }
        );


    }


    private String getRandomWebMessage() {
        welcome_array = this.getResources()
                .getStringArray(R.array.welcome_tips);
        int index = (int) (Math.random() * (welcome_array.length - 1));
        welcome_tip = welcome_array[index];
        return welcome_tip;
    }


    public void getDataUrl(String data) {
        // System.out.println(data);
        parseText(data);
    }

    public void parseText(String str) {
        try {
            JSONObject jb = new JSONObject(str);
            // System.out.println(jb.getString("code"));
            // System.out.println(jb.getString("text"));
            ChatData chatData;
            chatData = new ChatData(jb.getString("text"), ChatData.RECEIVER,
                    getTime());


            datas.add(chatData);
            adapter.notifyDataSetChanged();
        } catch (JSONException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

    /**
     * 发送消息的方法
     *
     * @param msg
     */
    public void send(String msg) {
        getTime();
        String content_str;
        content_str = msg;
        input.setText("");
        String dropk = content_str.replace(" ", "");
        String droph = dropk.replace("\n", "");
        ChatData chatData;
        time = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date());
        chatData = new ChatData(content_str, ChatData.SEND, time);
        msg=content_str;
        mLog.e("保存聊天好友到网络：" + id + cid + msg + time);
        addChatFriend();
        datas.add(chatData);
//        if (datas.size() > 30) {
//            for (int i = 0; i < datas.size(); i++) {
//                datas.remove(i);
//            }
//        }
        adapter.notifyDataSetChanged();
        list.setSelection(datas.size());
//        list.setSelection(datas.size());
//        httpData = (HttpData) new HttpData(
//                "http://www.tuling123.com/openapi/api?key=6af9822f5491fadfc142b53818bbd63a&info="
//                        + droph, this).execute();
    }

    long currentTime = 0;
    long oldTime = 0;

    private String getTime() {
        currentTime = System.currentTimeMillis();
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date curDate = new Date();
        String str = format.format(curDate);
        if (currentTime - oldTime >= 500) {
            oldTime = currentTime;
            return str;
        } else {
            return "";
        }

    }

    private Runnable mRunnable = new Runnable() {
        public void run() {
            //更新界面
            mHandler.obtainMessage().sendToTarget();
            //每2秒执行一次
//            mHandler.postDelayed(mRunnable, 2000);
        }

    };


    private Handler mHandler = new Handler() {
        @Override
        public void handleMessage(android.os.Message msg) {
            super.handleMessage(msg);
//
//            if(is){
//
//            }
//            recevie();//机器人随机发送一条消息
            getWebMessage("1", "1");


        }
    };

    /**
     * 接受机器人发送的消息的方法
     */
    private void recevie(String msg) {
        String content_str;
        content_str = getRandomWelcomeTips();
        String dropk = content_str.replace(" ", "");
        String droph = dropk.replace("\n", "");
        ChatData chatData;
        time = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date());
        chatData = new ChatData(msg, ChatData.RECEIVER, time);
        msg=content_str;
        mLog.e("保存聊天好友到网络：" + id + cid + msg + time);
        addChatFriend();
        datas.add(chatData);
//        if (datas.size() > 30) {
//            for (int i = 0; i < datas.size(); i++) {
//                datas.remove(i);
//            }
//        }
        adapter.notifyDataSetChanged();
        list.setSelection(datas.size());
    }
//
//    @Override
//    public boolean onKeyDown(int keyCode, KeyEvent event) {
//
//            if(flag.equals("0")){
//                //读取本地保存的id和password
//                String username= PreferencesUtils.getString(context,"jid","");
//
//                String password= PreferencesUtils.getString(context,"password","");
//
//                BmobUserManager.getInstance(context).login(username,password,new SaveListener() {
//                    @Override
//                    public void onSuccess() {
//
//                        android.util.Log.e("Demo", "进入到主界面");
//                        Intent mainIntent = new Intent().setClass(context, MyMainActivity.class);
//                        startActivity(mainIntent);
//                        finish();
//
//
//                    }
//
//                    @Override
//                    public void onFailure(int i, String s) {
//                        Toast.makeText(context, "登录失败", Toast.LENGTH_SHORT).show();
//
//                    }
//                });
//
//
//                startActivity(new Intent(context,MyMainActivity.class));
//                finish();
//            }else{
//                finish();
//            }
//
//
//
//
//
//
//
//        return true;
//    }

}
